package edu.xlh.travel.shiro.domin;


import edu.xlh.travel.dao.UserDao;
import edu.xlh.travel.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;


public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserDao userDao;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");

        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();

        //info.addStringPermission("user:add");
        //拿到当前用户登陆对象
        Subject subject= SecurityUtils.getSubject();
        User currentUser= (User) subject.getPrincipal();//拿到User对象
        info.addStringPermission(currentUser.getId());//设置当前用户对象

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证");

        //用户名，密码，数据库中获取

        DiyToken userToken=(DiyToken) authenticationToken;

        String phone = userToken.getPhone();
        String email = userToken.getEmail();

        User user = new User();
        if (!StringUtils.isEmpty(phone)) {
             user = (User)userDao.findByMobile(userToken.getPhone());//获取用户名
        } else if (!StringUtils.isEmpty(email)) {
             user = (User)userDao.findByEmail(email);
        } else {

        }
        String name = user.getName();
        String password = user.getPassword();
        if(user==null){//说明查无此人
            return null;
        }

        //密码认证,shiro做
        return new SimpleAuthenticationInfo(user,password , name);//放入User对象
    }

    /**
     * 限定这个 Realm 只处理 UsernamePasswordToken
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

}
